package com.library.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.library.bean.Admin;
import com.library.bean.Book;
import com.library.dao.BaseDao;
import com.library.dao.BookDao;

public class BookDaoImpl implements BookDao {

	public List<Book> selectAllBook(int pageNum,int pageSize) {
		List<Book> bookList = new ArrayList();
		String sql = "SELECT * FROM book LIMIT ?,?";
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setInt(1, (pageNum-1)*pageSize);
			ps.setInt(2, pageSize);
			res = ps.executeQuery();
			while(res.next()) {
				Book book = new Book();
				book.setBookId(res.getInt("bookId"));
				book.setBookName(res.getString("setBookName"));
				book.setBookNo(res.getString("setBookNo"));
				book.setBookNum(res.getInt("setBookNum"));
				book.setBookPrice(res.getInt("setBookPrice"));
				book.setBookType(res.getString("setBookType"));
				book.setBookWriter(res.getString("setBookWriter"));
				bookList.add(book);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(res, ps, con);
		}
		return bookList;
	}

	@Override
	public int selectBookNums() {
		int rows = 0;
		String sql = "SELECT count(1) as rows FROM book";
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			res = ps.executeQuery();
			if(res.next()) {
				rows = res.getInt("rows");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(res, ps, con);
		}
		return rows;
	}

	@Override
	public int deleteBookById(int bookId) {
		int row = 0;
		String sql = "DELETE FROM book WHERE bookId = ?";
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setInt(1, bookId);
			row = ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(res, ps, con);
		}
		return row;
	}

}
